package com.ruoyi.common.utils.uuid;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class NumCreateUtils {
    private final StringRedisTemplate redisTemplate;
    private static final String COUNTER_KEY = "order_number:counter";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    public NumCreateUtils(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String generateOrderNumber() {
        String today = LocalDate.now().format(DATE_FORMATTER);
        String key = today + ":" + COUNTER_KEY;

        // 使用Redis的INCR命令原子性递增
        Long current = redisTemplate.opsForValue().increment(key);
        if (current == null) {
            // 如果key不存在，先初始化为1（注意转换为String类型）
            redisTemplate.opsForValue().set(key, "1");  // 修正点：将1转换为字符串
            current = 1L;
        }

        return today + "-" + String.format("%06d", current);
    }
}

